<!-- 短租结算 -->
<template>
  <a-modal
    v-model:visible="showModal"
    @close="onClose"
    @before-ok="beforeSubmitFn"
    @before-open="onBeforeOpen"
    title="结算"
    class="modal-dialog-wrapper"
    unmount-on-close
    :mask-closable="false"
    width="85vw"
  >
    <div class="fee-page">
      <a-descriptions :size="'medium'" :column="3" :align="{ label: 'right' }">
        <a-descriptions-item label="订单号">
          <div style="width: 25vw">
            <span class="mr-2">
              <a-tag size="mini" v-if="orderDetails?.orderCode" color="#1890FF">自有</a-tag> {{ orderDetails?.orderCode || '-' }}
            </span>
            <span v-if="orderDetails.orderSource == 2">
              <a-tag size="mini" color="#1890FF">渠道</a-tag> {{ orderDetails.channelOrderCode }}
            </span>
            <span class="blue" v-if="orderDetails.returnCarInfoDto">（已还车）</span>
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="承租人">
          {{ orderDetails?.memberName || '-' }} | {{ orderDetails?.memberPhone || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="车辆">
          {{ orderDetails?.carLicenseNo || '-' }}
          <a-tag color="red" v-if="orderDetails.orderCarLabel">{{ orderDetails.orderCarLabel }}</a-tag></a-descriptions-item
        >
        <a-descriptions-item label="租赁周期">
          {{ orderDetails.startTime }} - {{ orderDetails.endTime }}
          <span class="blue" v-if="orderDetails?.rentDays">（{{ orderDetails?.rentDays }}）</span>
        </a-descriptions-item>
        <a-descriptions-item label="交车人">{{ orderDetails?.giveStaffName || '-' }}</a-descriptions-item>
        <a-descriptions-item label="还车人">{{ orderDetails?.returnStaffName || '-' }}</a-descriptions-item>
        <a-descriptions-item label="取车门店">{{ orderDetails?.siteName || '-' }}</a-descriptions-item>
        <a-descriptions-item label="还车门店">{{ orderDetails?.returnSiteName || '-' }}</a-descriptions-item>
      </a-descriptions>

      <a-divider class="custom-divider" />

      <!-- 表格 -->
      <table-index :table="tableCompulsory">
        <template #settlementAmount="{ record }">
          <a-input-number
            placeholder="请输入"
            :precision="2"
            :min="0"
            :max="99999999.99"
            hide-button
            :error="record.errorStatus"
            @blur="blurFn($event, record)"
            v-model="record.settlementAmount"
          />
          <div v-if="record.errorStatus" class="errorStatus">{{ record.errorMsg }}</div>
        </template>
        <template #remark="{ record }">
          <div class="all-remark">
            {{ record.remark || '-' }}
          </div>
          <a-link v-if="record.remark" @click="onShowMoreRemark(record)">查看更多</a-link>
        </template>
      </table-index>
      <div class="summary">
        <p>本次结算总额：{{ currentTotalObj.total }} 元</p>
        <p>
          收款：{{ currentTotalObj.collection }} 元（线下费用 {{ currentTotalObj.collection_offline }} 元 + 线上费用
          {{ currentTotalObj.collection_online }} 元） 付款：{{ currentTotalObj.pay }} 元 （线下费用 {{ currentTotalObj.pay_offline }} 元 +
          线上费用 {{ currentTotalObj.pay_online }} 元）</p
        >
      </div>

      <page-form :model="form" layout="vertical" ref="formRef" style="margin-top: 60px">
        <page-form-row>
          <page-form-item
            field="paymentWay"
            label="结算方式"
            :rules="{ required: true, message: '请选择结算方式' }"
            labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              placeholder="请选择"
              v-model="form.paymentWay"
              @change="typeChange"
              :disabled="disabledCostType"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option v-for="item in paywayEnum" :key="item.way" :value="item.way" :label="item.wayStr" />
            </a-select>
          </page-form-item>
          <template v-if="form.paymentWay">
            <page-form-item
              v-if="form.paymentWay && form.paymentWay != -1"
              field="paymentTime"
              label="结算时间"
              :rules="[{ required: true, message: '请选择结算时间', trigger: 'change' }]"
            >
              <i-date-picker
                class="w-full"
                v-model="form.paymentTime"
                show-time
                value-format="YYYY-MM-DD HH:mm:ss"
                :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
                popup-container="#app"
              />
            </page-form-item>
            <page-form-item v-if="form.paymentWay == -1" field="account" label="结算主体" :rules="{ required: true, message: '请选择' }">
              <a-select
                :placeholder="'请选择'"
                v-model="form.account"
                :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
                allow-clear
                popup-container="#app"
              >
                <a-option v-for="item in accountList" :key="item.id" :value="item.id" :label="item.bank" />
              </a-select>
            </page-form-item>
            <page-form-item
              v-else
              field="account"
              label="结算账号"
              labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。"
            >
              <a-select
                :placeholder="!form.paymentWay ? '请先选择结算方式' : '请选择'"
                v-model="form.account"
                :disabled="!form.paymentWay ? true : false"
                :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
                allow-clear
                popup-container="#app"
              >
                <a-option
                  v-for="item in accountList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.account + (item.bank ? '_' + item.bank : '')"
                />
              </a-select>
            </page-form-item>
            <page-form-item
              v-if="form.paymentWay == 4"
              label="选择使用哪笔订单押金"
              field="deductionOrderId"
              :rules="{ required: true, validator: validateName, trigger: 'change' }"
            >
              <template #label-extra>
                <div v-if="form.deductionOrderId">
                  <a class="a-link" @click="onShowDeposit"> 查看押金详情 </a>
                </div>
              </template>
              <a-select
                placeholder="请选择"
                v-model="form.deductionOrderId"
                :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
                allow-clear
                popup-container="#app"
              >
                <a-option v-for="(item, index) in memberList" :key="index" :value="item.orderId"> {{ item.orderCode }}</a-option>
              </a-select>
            </page-form-item>
            <page-form-item field="customerName" label="客户名称" :rules="{ required: true, message: '请输入客户名称' }">
              <i-input placeholder="请输入" v-model="form.customerName" :max-length="20" />
            </page-form-item>
            <page-form-item field="customerAccount" :label="costName == '收款' ? '客户付款账号' : '客户收款账号'">
              <i-input placeholder="请输入" v-model="form.customerAccount" :max-length="20" />
            </page-form-item>
            <page-form-item field="settlementRemark" label="结算备注">
              <i-input placeholder="请输入" v-model="form.settlementRemark" :max-length="200" />
            </page-form-item>
            <page-form-item field="fileIdList" label="上传凭证" size="1">
              <upload-img v-model="form.fileIdList" limit="10" />
            </page-form-item>
          </template>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button type="primary" @click="beforeSubmitFn" :loading="okLoading">确认</a-button>
      </a-space>
    </template>
  </a-modal>

  <qcode-modal v-model:visible="payQCodeModal" @close="payQCodeClose" :details="qrCodeDetails" :from="qrCodeFrom" />
  <!-- 查看更多备注 -->
  <a-modal
    width="45vw"
    v-model:visible="showMoreRemarkModal"
    title="备注"
    ok-text="关闭"
    hide-cancel
    @before-open="beforeOpenRemark"
    @ok="showMoreRemarkModal = false"
  >
    <table-index :table="tableRemark" />
  </a-modal>
  <a-modal title="提示" v-model:visible="confirmVisible" @ok="submitFn"> 结算费项中包含线上费用及线下费用，是否确认合并结算？ </a-modal>
  <!-- 查看押金详情 -->
  <ZhimaDepositFreeModal :orderId="form.deductionOrderId" :showOperateBtn="false" ref="zhimaDepositFreeModalRef" />
</template>

<script setup name="ShortOrderConfirmFees" lang="ts">
  import qcodeModal from '../modals/qcode-modal.vue'
  import ZhimaDepositFreeModal from '../../order/short-order/components/alipay-deposit/zhima-deposit-free-modal.vue'
  import { Message } from '@arco-design/web-vue'
  import {
    getAccountByPageData,
    getAccountByWayAndType,
    feetoConfirm,
    feeSubmit,
    remarkLogList,
    getUsableAmountOrderList,
  } from '@/api/order/sOrder'
  import { computed, nextTick, ref } from 'vue'
  import { useTable } from '@/hooks/table'
  import useUserStore from '@/store/modules/user'
  import dayjs from 'dayjs'

  const userStore = useUserStore()
  const paywayEnum = ref<any>([]) //收付款方式
  const accountList = ref<any>([]) //收付款账号列表
  const costType = ref() // 收支类型 10 收款 20 付款
  const costName = ref('')
  const feeList = ref<any>([]) // 收付款列表
  const feeCostAmount = ref<any>({}) //收付款类型及金额
  const formRef = ref()
  const disabledCostType = ref(false)
  const payQCodeModal = ref(false)
  const form = ref<any>({
    idList: [], //结算单ids
  })
  const validateName = (value, cb) => {
    console.log(value)
    if (!value || value == '') {
      cb('请选择使用哪笔订单押金')
      return false
    } else {
      memberList.value.map((item) => {
        if (item.orderId == value) {
          if (item.availableDepositAmount < currentTotalObj.value.total) {
            cb('押金金额不足，请修改本次结算金额')
            return false
          }
        }
      })
    }
  }
  const onBeforeOpen = () => {
    userStore.setEpDetail()
  }
  // table 配置
  const tableCompulsory = useTable({
    pagination: false,
    columns: [
      { title: '费用名称', dataIndex: 'itemName' },
      { title: '操作节点', dataIndex: 'createNodeName' },
      { title: '结算状态', dataIndex: 'feeStatusName' },
      { title: '费用类型', dataIndex: 'feeTypeName' },
      { title: '收支类型', dataIndex: 'costTypeName' },
      { title: '总额(元)', dataIndex: 'amount' },
      { title: '实结(元)', dataIndex: 'payAmount' },
      { title: '佣金(元)', dataIndex: 'commissionAmount' },
      { title: '未结(元)', dataIndex: 'waitPayAmount', headerCellClass: 'tableCommonRed', bodyCellClass: 'tableCommonRed' },
      { title: '本次结算金额(元)', slotName: 'settlementAmount', width: 150 },
      { title: '备注', dataIndex: 'remark', slotName: 'remark' },
    ],
    dataList: [],
  })
  // 打开弹窗
  const okLoading = ref(false)
  const showModal = ref(false)
  const show = (idList: any, record: any) => {
    // 重置
    resetForm()
    showModal.value = true
    form.value.idList = JSON.parse(idList)
    if (form.value.idList) {
      feeConfirm(form.value.idList)
    }
  }
  // 失焦
  const blurFn = (e: { target: { value: string | number } }, record: { errorStatus: boolean; waitPayAmount: number; errorMsg: string }) => {
    record.errorStatus = e.target.value > record.waitPayAmount || ['', '.'].includes(e.target.value)
    if (['', '.'].includes(e.target.value)) {
      record.errorMsg = '请填写本次结算金额'
    } else if (e.target.value > record.waitPayAmount) {
      record.errorMsg = '本次结算金额需小于等于未结金额'
    } else {
      record.errorMsg = ''

      // 触发 deductionOrderId 是否满足的校验，用于更新提示语
      formRef.value.validateField('deductionOrderId')
    }
  }
  // 查看备注
  const currentRemark = ref<any>({})
  const showMoreRemarkModal = ref(false)
  const tableRemark = useTable({
    tableLoading: false,
    pagination: false,
    columns: [
      { title: '创建时间', dataIndex: 'createTime' },
      { title: '操作人', dataIndex: 'createUserName' },
      { title: '备注信息', dataIndex: 'operateLog' },
    ],
  })
  const beforeOpenRemark = () => {
    remarkLogList({ orderId: currentRemark.value.orderId, id: currentRemark.value.id }).then((res: any) => {
      tableRemark.dataList = res.result
    })
  }
  const onShowMoreRemark = (record: any) => {
    console.log('onShowMoreRemark', record)
    currentRemark.value = record
    showMoreRemarkModal.value = true
  }
  const payQCodeClose = () => {
    emit('feepageConfirm')
  }

  const onClose = () => {
    showModal.value = false
    okLoading.value = false
  }
  const resetForm = () => {
    disabledCostType.value = false
    paywayEnum.value = []
    accountList.value = []
    form.value = {}
    okLoading.value = false
    tableCompulsory.dataList = []
    orderDetails.value = {}
  }
  // 计算当前输入金额
  const currentTotalObj = computed(() => {
    let total = 0, // 本次结算总额
      pay = 0, // 付款
      collection = 0, // 收款
      pay_online = 0, //付款线上支付
      pay_offline = 0, // 付款线下支付
      collection_online = 0, // 收款线上支付
      collection_offline = 0 //收款线下支付
    tableCompulsory.dataList.map((it: any) => {
      // 付款=20 收款=10 线下费用：feeType == 1
      if (it.costType == 20) {
        pay += it.settlementAmount * 1000
        it.feeType == 1 ? (pay_offline += it.settlementAmount * 1000) : (pay_online += it.settlementAmount * 1000)
      } else {
        collection += it.settlementAmount * 1000
        it.feeType == 1 ? (collection_offline += it.settlementAmount * 1000) : (collection_online += it.settlementAmount * 1000)
      }
    })
    total = collection - pay
    // 收款及付款合并结算，结算金额变为负数时，需判断当前选择的结算方式是否满足
    getType(total >= 0 ? 10 : 20, feeList.value, total)
    return {
      total: total / 1000 || 0,
      pay: pay / 1000 || 0,
      collection: collection / 1000 || 0,
      pay_online: pay_online / 1000 || 0,
      pay_offline: pay_offline / 1000 || 0,
      collection_online: collection_online / 1000 || 0,
      collection_offline: collection_offline / 1000 || 0,
    }
  })
  // 订单详情
  const orderDetails = ref({})
  // 根据承租人ID获取可用押金订单列表
  const memberList = ref([])
  // 结算
  const feeConfirm = (ids: any) => {
    feetoConfirm({ idList: ids })
      .then(({ result }) => {
        feeCostAmount.value = result
        result.orderFeeList.map((it: { settlementAmount: any; waitPayAmount: any; errorStatus: boolean }) => {
          it.settlementAmount = it.waitPayAmount
          it.errorStatus = false
        })
        feeList.value = result.orderFeeList
        orderDetails.value = result.shortOrder
        form.value.actualAmount = Math.abs(result.receiveAmount) //固定金额，不可修改
        costType.value = result.costType
        form.value.paymentTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        form.value.customerName = result.shortOrder.memberName
        if (costType.value == 10) {
          costName.value = '收款'
        } else {
          costName.value = '付款'
        }
        // 押金抵扣为固定收付款方式
        if (feeCostAmount.value.payType != null) {
          disabledCostType.value = true
          form.value.paymentWay = feeCostAmount.value.payType.toString()
        }
        tableCompulsory.dataList = feeList.value
        //获取可用押金订单列表
        getUsableAmountOrderList({
          memberId: result.shortOrder.memberId,
          orderId: result.orderId,
          orderType: 1, // 1短租 0长租
          payTypeList: [4], //4 芝麻免押
        }).then((res: any) => {
          if (res.code == 200) {
            memberList.value = res.result
            handleDeductionDefaultSelect()
          }
        })
      })
      .finally(() => {
        tableCompulsory.tableLoading = false
      })
  }

  // 处理押金默认选中本单
  const handleDeductionDefaultSelect = () => {
    // 存在可用押金列表并且选中结算方式选中了押金抵扣
    if (memberList.value && memberList.value.length > 0 && form.value.paymentWay == 4) {
      // 当前的订单id
      const currOrderId = feeCostAmount.value.orderId
      memberList.value.forEach((item: any) => {
        if (item.orderId == currOrderId) {
          form.value.deductionOrderId = item.orderId
          // 触发 deductionOrderId 是否满足的校验，用于更新提示语
          nextTick(() => {
            formRef.value.validateField('deductionOrderId')
          })
        }
      })
    }
  }

  // 查看押金详情
  const zhimaDepositFreeModalRef = ref()
  const onShowDeposit = () => {
    zhimaDepositFreeModalRef.value.show()
  }

  // 收付款类型
  const getType = (costType: any, orderFeeList = [], total: any) => {
    console.log('getType: ', costType, orderFeeList)

    // 是否包含线下费用
    const is_offline = orderFeeList.every((item: any) => item.feeType == 1)
    console.log('is_offline', is_offline)

    // 是否为收款
    const is_collection = orderFeeList.every((item: any) => item.costType == 10)
    console.log('is_collection', is_collection, 1, form.value.actualAmount)

    // 是否包含租车押金和违章押金
    const is_contain_rent_violation = orderFeeList.some((item: any) => item.feeNameId == 12 || item.feeNameId == 13)
    console.log('is_contain_rent_violation', is_contain_rent_violation)

    let is_show_jialian = false
    if (orderFeeList.length == 1 && is_collection && total > 0) {
      is_show_jialian = true
    } else if (orderFeeList.length > 1) {
      if (is_collection && total > 0) {
        is_show_jialian = true
      } else if (!is_collection && total > 0) {
        is_show_jialian = true
      }
    }
    console.log('is_show_jialian', is_show_jialian)

    const syncInventory: any = userStore.syncInventory

    getAccountByPageData({ type: costType == 10 ? 0 : 1 }).then((res: any) => {
      const data = res.result

      console.log('getAccountByPageData: ', syncInventory.jialianEnabled, form.value.actualAmount)

      // 订单不显示押金抵扣和预授权  4- 押金抵扣 5-预授权
      // paywayEnum.value = data.filter((i: any) => i.way != '4' && i.way != '5')
      paywayEnum.value = data.filter((i: any) => i.way != '5')

      // costType: 10 收款 20 付款
      // i.type: 0 收款 1 付款 2收款&付款
      if (costType == 10) {
        paywayEnum.value = paywayEnum.value.filter((i: any) => i.type != '1')
      } else {
        paywayEnum.value = paywayEnum.value.filter((i: any) => i.type != '0')
      }
      // 未结金额为负数时，本次结算为付款，相反为收款
      if (total != 0) {
        paywayEnum.value = paywayEnum.value.filter((i: any) => (i.type != total < 0 ? '0' : '1'))
      }

      /**
       * 不显示嘉联聚合支付
       * syncInventory.jialianEnabled: 0 未开通嘉联聚合支付
       * total: 收款金额小于等于0
       * is_offline: 不是线下费用时
       * is_show_jialian: 是否显示嘉联聚合支付，默认不显示
       * is_contain_rent_violation: 是否包含租车押金和违章押金
       */
      if (syncInventory.jialianEnabled == 0 || !is_show_jialian || !is_offline || is_contain_rent_violation) {
        paywayEnum.value = paywayEnum.value.filter((el: any) => el.way != '-1')
      }
      /**
       * 此处逻辑：
       * 金额大于等于0，接口返回收款的结算类型，小于0，接口返回付款的结算类型
       * 但是金额等于0的时候也不能显示押金扣款
       */
      if (total <= 0) {
        paywayEnum.value = paywayEnum.value.filter((el: any) => el.way != '4')
      }
      // 退款抵扣违约金仅在取消时，退款及违约金自动抵扣时使用，其他环节及费项不允许选择该收支方式
      paywayEnum.value = paywayEnum.value.filter((el: any) => el.way != '-2')
      // 如果下拉选项中不存在当前结算方式 => 清空
      if (!paywayEnum.value.find((it: { way: any }) => it.way == form.value.paymentWay)) form.value.paymentWay = ''
    })
  }
  // 账号
  const typeChange = (e: any) => {
    if (e) {
      form.value.account = ''
    }

    paywayEnum.value.forEach((el: any) => {
      if (el.way == e) {
        getAccountByWayAndType({ way: Number(el.way), type: costType.value == 10 ? 0 : 1 }).then((res: any) => {
          if (res.result.length == 1 && form.value.paymentWay == -1) {
            form.value.account = res.result[0].id
          }

          accountList.value = res.result
        })
      }
    })

    // 如果结算方式是押金抵扣
    if (e == 4) {
      handleDeductionDefaultSelect()
    }
  }
  defineExpose({
    show,
  })
  const emit = defineEmits(['feepageConfirm'])

  const qrCodeDetails = ref()
  const qrCodeFrom = ref('')
  // 存在线上线下费用时，弹窗提示
  const confirmVisible = ref(false)
  const beforeSubmitFn = () => {
    let settlementAmountErrorObj = tableCompulsory.dataList.find((it: { errorStatus: boolean }) => it.errorStatus == true)
    if (settlementAmountErrorObj) return Message.error(settlementAmountErrorObj.errorMsg)
    // 判断是否同时存在线上及线下费用
    let costTypeArr = tableCompulsory.dataList.map((it: { feeType: any }) => it.feeType)
    confirmVisible.value = costTypeArr.includes(1) && costTypeArr.includes(2)
    if (confirmVisible.value) return
    submitFn()
  }

  const submitFn = () => {
    okLoading.value = true
    formRef.value.validate((error: any) => {
      if (!error) {
        const param = {
          ...form.value,
          orderId: feeCostAmount.value.orderId,
          orderFeeList: feeList.value.map((it: { id: any; settlementAmount: any }) => {
            return {
              id: it.id,
              settlementAmount: it.settlementAmount,
            }
          }),
        }
        feeSubmit(param)
          .then((res: any) => {
            if (form.value.paymentWay == -1) {
              qrCodeFrom.value = 'orderConfirmFee'
              qrCodeDetails.value = { qrcodeId: res.result }
              showModal.value = false
              payQCodeModal.value = true
            } else {
              Message.success(res.message)
              showModal.value = false
              emit('feepageConfirm')
            }
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        okLoading.value = false
      }
    })
  }
</script>

<style lang="less" scoped>
  .blue {
    color: #1890ff;
  }
  .errorStatus {
    font-size: 12px;
    color: #f53f3f;
  }
  .all-remark {
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 1;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }
  .summary {
    padding: 12px 20px;
    border: 1px rgba(229, 231, 235, 0.5) solid;
    border-top: none;
    font-weight: 500;
    font-size: 16px;
    color: #1890ff;
  }

  .fee-list {
    padding-top: 20px;
    border: 1px solid #f2f3f5;
  }

  .all-cost {
    font-weight: 600;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    background: #f2f3f5;
    height: 100px;

    .cost-num {
      color: #1890ff;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
    }
  }

  // 弹窗添加的样式
  .fee-page {
    width: 100%;
    max-height: 70vh;
    position: relative;

    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }

    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }

    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
</style>
<style>
  .tableCommonRed {
    .arco-table-th-title,
    .arco-table-td-content {
      color: #f53f3f !important;
    }
  }
  .a-link {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #1890ff;
    text-align: right;
    font-style: normal;
    text-transform: none;
    cursor: pointer;
  }
</style>
